package com.it.tydic.estate.module.controller.common;

import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.constants.Constants;
import com.it.tydic.estate.common.util.IPUtil;
import com.it.tydic.estate.common.util.InstaIdGenerator;
import com.it.tydic.estate.common.util.TimeUtil;
import com.it.tydic.estate.module.model.inner.TbLoginLog;
import com.it.tydic.estate.module.model.inner.TbUser;
import com.it.tydic.estate.module.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("login")
@Api("登录接口")
public class LoginController {

    @Autowired
    private UserService userService;


    private static final Logger logger=  LoggerFactory.getLogger(LoginController.class);

    @GetMapping("/get/{id}")
    @ApiOperation(value = "根据id查询用", notes = "查询数据库中的某个用户")
    @ApiImplicitParam(name = "id", value = "用户id",  paramType = "path", required = true, dataType =  "Integer")
    public String getUser(@PathVariable int id) { //@PathVariable 获取/get/{id}中id
        logger.info("sucess");
        return "sucess";
    }

    @PostMapping(value = "/loginCheck",produces = "application/json;charset=utf-8")
    @ApiOperation(value = "登录验证接口")
    public Result loginCheck(@RequestBody Map<String,String> loginParam,HttpServletRequest request, HttpSession session)
          {
             String userName= loginParam.get("userName");
            TbUser user = userService.findByUserName(userName);
            if (user != null) {
                request.getSession().setAttribute(Constants.CURRENTUSER, user);;
                saveLogin(user,request);
                //查询用户所属角色
                List<String> roleIds= userService.findRolesByUserId(user.getUserId());
                if(roleIds.size() > 0){
                    user.setRoleIds(roleIds);
                }
                logger.info("session succesful");
                logger.info("用户" + userName + "登录成功");
            } else {
                logger.info("用户" + userName + "登录失败！");
                return   Result.error(CodeMsg.EMPTY_PARAM_ERROR);
            }
        return Result.success(user);
    }

    // 记录登录日志
    public void saveLogin(TbUser user, HttpServletRequest request) {
        // 添加登录日志
        TbLoginLog loginLog = new TbLoginLog();
        InstaIdGenerator idGenerator = new InstaIdGenerator();
        loginLog.setId(idGenerator.nextId(TimeUtil.timeGen())+"");
        loginLog.setUserId(user.getUserId());
        loginLog.setUserName(user.getUserName());
        String ip = IPUtil.getIp(request);
        loginLog.setLoginIp(ip);
        loginLog.setCreateTime(new Date());
        loginLog.setSessionId(request.getSession().getId());
        loginLog.setUserAgen(request.getHeader("User-Agent"));
        Constants.loginLogQueue.offer(loginLog);
    }

}
